<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>待考试 - 智慧教育考试系统</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

  <!-- 配置Tailwind自定义主题 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            secondary: '#36D399',
            accent: '#FF9F43',
            neutral: '#F8FAFC',
            'neutral-dark': '#334155',
            'status-pending': '#FFB800',
            'status-active': '#36D399',
            'status-expired': '#94A3B8'
          },
          fontFamily: {
            inter: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>

  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .card-shadow {
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      }
      .nav-hover {
        @apply transition-all duration-300 hover:bg-primary/10 hover:text-primary;
      }
      .btn-primary {
        @apply bg-primary text-white px-4 py-2 rounded-lg transition-all duration-300 hover:bg-primary/90 active:bg-primary/80;
      }
      .btn-secondary {
        @apply bg-white border border-gray-200 text-neutral-dark px-4 py-2 rounded-lg transition-all duration-300 hover:bg-gray-50 active:bg-gray-100;
      }
      .btn-exam {
        @apply bg-secondary text-white px-3 py-1.5 rounded-lg transition-all duration-300 hover:bg-secondary/90 active:bg-secondary/80;
      }
      .countdown {
        @apply inline-flex items-center justify-center px-2 py-1 text-xs font-medium rounded-full bg-red-100 text-red-600;
      }
    }
  </style>
</head>
<body class="font-inter bg-gray-50 text-neutral-dark min-h-screen flex flex-col">
  <!-- 顶部导航栏 -->
  <header class="bg-white border-b border-gray-200 sticky top-0 z-30">
    <div class="container mx-auto px-4 py-3 flex items-center justify-between">
      <div class="flex items-center space-x-2">
        <i class="fa fa-graduation-cap text-primary text-2xl"></i>
        <h1 class="text-xl font-bold text-primary">智慧教育考试系统</h1>
      </div>

      <div class="flex items-center space-x-6">
        <div class="hidden md:flex items-center space-x-4">
          <button class="text-gray-500 hover:text-primary transition-colors relative">
            <i class="fa fa-bell-o"></i>
            <span class="absolute -top-1 -right-1 w-4 h-4 bg-accent text-white text-xs rounded-full flex items-center justify-center">3</span>
          </button>
          <button class="text-gray-500 hover:text-primary transition-colors">
            <i class="fa fa-cog"></i>
          </button>
        </div>

        <div class="flex items-center space-x-2">
          <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary">
            <i class="fa fa-user"></i>
          </div>
          <span class="hidden md:inline">{{ student.name if student else '学生' }}</span>
        </div>
      </div>
    </div>
  </header>

  <!-- 主内容区 -->
  <main class="flex-1 flex flex-col md:flex-row">
    <!-- 左侧导航 -->
    <aside class="w-full md:w-64 bg-white border-r border-gray-200 md:h-[calc(100vh-60px)] sticky md:sticky top-[60px] z-20">
      <!-- 角色切换 -->
      <div class="p-4 border-b border-gray-200">
        <h2 class="text-sm font-medium text-gray-500 mb-2">角色切换</h2>
        <div class="flex rounded-lg overflow-hidden border border-gray-200">
          <button id="teacher-tab" class="flex-1 py-2 px-3 bg-white text-gray-600 text-sm font-medium hover:bg-gray-50">
            教师端
          </button>
          <button id="student-tab" class="flex-1 py-2 px-3 bg-primary text-white text-sm font-medium">
            学生端
          </button>
        </div>
      </div>

      <!-- 教师导航菜单 (默认隐藏) -->
      <nav id="teacher-nav" class="p-2 hidden">
        <ul class="space-y-1">
          <li>
            <a href="/home" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-bar-chart w-5 text-center"></i>
              <span>教师控制台</span>
            </a>
          </li>
          <li>
            <a href="/Publish_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-pencil-square-o w-5 text-center"></i>
              <span>发布考试</span>
            </a>
          </li>
          <li>
            <a href="/History_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-history w-5 text-center"></i>
              <span>历史考试</span>
            </a>
          </li>
          <li>
            <a href="/Set_questions" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-magic w-5 text-center"></i>
              <span>一键出题</span>
            </a>
          </li>
          <li>
            <a href="/Question_Bank" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-book w-5 text-center"></i>
              <span>题库管理</span>
            </a>
          </li>
          <li>
            <a href="/stu_management" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-users w-5 text-center"></i>
              <span>学生管理</span>
            </a>
          </li>
          <li>
            <a href="/class_management" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-th-large w-5 text-center"></i>
              <span>班级管理</span>
            </a>
          </li>
        </ul>
      </nav>

      <!-- 学生导航菜单 -->
      <nav id="student-nav" class="p-2">
        <ul class="space-y-1">
          <li>
            <a href="/Exam_record" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-file-text-o w-5 text-center"></i>
              <span>个人考试记录</span>
            </a>
          </li>
          <li>
            <a href="/Waiting_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover text-primary bg-primary/10">
              <i class="fa fa-clock-o w-5 text-center"></i>
              <span>待考试</span>
              <span class="ml-auto bg-accent text-white text-xs px-2 py-0.5 rounded-full">{{ exams|length }}</span>
            </a>
          </li>
          <li>
            <a href="/Mistake_question" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-exclamation-circle w-5 text-center"></i>
              <span>错题本</span>
            </a>
          </li>
        </ul>
      </nav>
    </aside>

    <!-- 右侧内容区 -->
    <div class="flex-1 p-4 md:p-6 overflow-auto">
      <div class="mb-6">
        <div class="flex items-center">
          <a href="#" class="text-gray-500 hover:text-primary mr-2">
            <i class="fa fa-arrow-left"></i>
          </a>
          <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold">待考试</h2>
        </div>
        <p class="text-gray-500 mt-1">查看所有即将开始的考试，做好准备并按时参加</p>
      </div>

      <!-- 搜索区域 -->
      <form id="search-form" class="bg-white rounded-xl p-5 card-shadow mb-6">
        <div class="flex flex-col md:flex-row flex-wrap gap-4">
          <div class="w-full md:w-auto flex items-center gap-3">
            <label class="text-sm font-medium text-gray-700">考试类型：</label>
            <select id="exam-type" name="exam_type" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
              <option value="全部类型" {% if exam_type_filter == '全部类型' or not exam_type_filter %}selected{% endif %}>全部类型</option>
              <option value="周测" {% if exam_type_filter == '周测' %}selected{% endif %}>周测</option>
              <option value="月考" {% if exam_type_filter == '月考' %}selected{% endif %}>月考</option>
              <option value="期中/期末考试" {% if exam_type_filter == '期中/期末考试' %}selected{% endif %}>期中/期末考试</option>
              <option value="自定义考试" {% if exam_type_filter == '自定义考试' %}selected{% endif %}>自定义考试</option>
            </select>
          </div>

          <div class="w-full md:w-auto flex items-center gap-3">
            <label class="text-sm font-medium text-gray-700">学科：</label>
            <select id="subject" name="subject" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
              <option value="全部学科" {% if subject_filter == '全部学科' or not subject_filter %}selected{% endif %}>全部学科</option>
              <option value="数学" {% if subject_filter == '数学' %}selected{% endif %}>数学</option>
              <option value="语文" {% if subject_filter == '语文' %}selected{% endif %}>语文</option>
              <option value="英语" {% if subject_filter == '英语' %}selected{% endif %}>英语</option>
              <option value="物理" {% if subject_filter == '物理' %}selected{% endif %}>物理</option>
              <option value="化学" {% if subject_filter == '化学' %}selected{% endif %}>化学</option>
            </select>
          </div>

          <div class="w-full md:flex-1 relative">
            <input type="text" id="keyword" name="keyword" placeholder="搜索考试名称..." 
                   value="{{ keyword_filter or '' }}"
                   class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
            <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
          </div>

          <div class="w-full md:w-auto flex gap-2">
            <button type="submit" class="btn-primary">
              <i class="fa fa-search mr-1"></i>搜索
            </button>
            <button type="button" id="reset-btn" class="btn-secondary">
              <i class="fa fa-refresh mr-1"></i>重置
            </button>
          </div>
        </div>
      </form>

      <!-- 待考试表格 -->
      <div class="bg-white rounded-xl card-shadow overflow-hidden">
        <div class="overflow-x-auto">
          <table class="w-full min-w-[800px]">
            <thead>
              <tr class="bg-gray-50 text-left">
                <th class="px-6 py-4 text-sm font-medium text-gray-600">序号</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">考试名称</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">考试类型</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">学科</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">开始时间</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">结束时间</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">时长</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">状态</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600 text-right">操作</th>
              </tr>
            </thead>
            <tbody class="divide-y divide-gray-100">
              {% if exams %}
              {% for exam in exams %}
              <tr class="hover:bg-gray-50 transition-colors">
                <td class="px-6 py-4 text-sm text-gray-700">{{ loop.index }}</td>
                <td class="px-6 py-4 text-sm">
                  <div class="flex items-center">
                    <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary mr-2">
                      <i class="fa fa-file-text-o"></i>
                    </div>
                    <span class="font-medium">{{ exam.exam_name }}</span>
                  </div>
                </td>
                <td class="px-6 py-4 text-sm text-gray-700">{{ exam.exam_type or '未分类' }}</td>
                <td class="px-6 py-4 text-sm text-gray-700">{{ exam.subject or '' }}</td>
                <td class="px-6 py-4 text-sm text-gray-700">{{ exam.start_time_text }}</td>
                <td class="px-6 py-4 text-sm text-gray-700">{{ exam.end_time_text }}</td>
                <td class="px-6 py-4 text-sm text-gray-700">{{ exam.duration_text }}</td>
                <td class="px-6 py-4">
                  <span class="inline-flex items-center justify-center px-2 py-1 text-xs font-medium rounded-full {{ exam.status_badge_class }}">
                    <i class="fa fa-clock-o mr-1"></i> {{ exam.status_display }}
                  </span>
                </td>
                <td class="px-6 py-4 text-right">
                  <button
                   class="btn-exam text-sm flex items-center justify-center gap-1"
                    data-exam-id="{{ exam.id }}"
                    data-exam-name="{{ exam.exam_name }}"
                    data-status-text="{{ exam.status_display }}"
                    data-can-start="{{ 'true' if exam.can_start else 'false' }}"
                    data-is-in-progress="{{ 'true' if exam.is_in_progress else 'false' }}"
                    data-start-url="{{ exam.start_url }}"
                    {% if not exam.can_start %}data-disabled-reason="考试尚未开始或已结束"{% endif %}
                    type="button"
                  >
                    <i class="fa fa-play"></i>
                    <span>
                      {% if exam.is_in_progress %}继续考试{% elif exam.can_start %}准备参加{% else %}查看状态{% endif %}
                    </span>
                  </button>
                </td>
              </tr>
              {% endfor %}
              {% else %}
              <tr>
                <td colspan="9" class="px-6 py-6 text-center text-sm text-gray-500">暂无待参加的考试，请耐心等待教师安排。</td>
              </tr>
              {% endif %}
            </tbody>
          </table>
        </div>

        <!-- 分页 -->
        <div class="px-6 py-4 border-t border-gray-100 flex flex-col sm:flex-row justify-between items-center">
          <p class="text-sm text-gray-500 mb-4 sm:mb-0">显示 1 至 5 条，共 8 条记录</p>
          <div class="flex items-center space-x-1">
            <button class="w-9 h-9 flex items-center justify-center rounded border border-gray-200 text-gray-500 hover:border-primary hover:text-primary disabled:opacity-50 disabled:cursor-not-allowed" disabled>
              <i class="fa fa-angle-left"></i>
            </button>
            <button class="w-9 h-9 flex items-center justify-center rounded bg-primary text-white">1</button>
            <button class="w-9 h-9 flex items-center justify-center rounded border border-gray-200 hover:border-primary hover:text-primary">2</button>
            <button class="w-9 h-9 flex items-center justify-center rounded border border-gray-200 text-gray-700 hover:border-primary hover:text-primary">
              <i class="fa fa-angle-right"></i>
            </button>
          </div>
        </div>
      </div>

      <!-- 考试须知卡片 -->
      <div class="mt-6 bg-blue-50 border border-blue-100 rounded-xl p-5">
        <div class="flex">
          <div class="flex-shrink-0">
            <i class="fa fa-info-circle text-primary text-xl"></i>
          </div>
          <div class="ml-3">
            <h3 class="text-sm font-medium text-blue-800">考试须知</h3>
            <div class="mt-2 text-sm text-blue-700 space-y-1">
              <p>• 请在考试开始前做好准备，保持网络畅通</p>
              <p>• 考试开始后，请勿刷新页面或关闭浏览器</p>
              <p>• 如遇技术问题，请及时联系老师</p>
              <p>• 考试时间结束后，系统将自动提交试卷</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </main>

  <!-- 页脚 -->
  <footer class="bg-white border-t border-gray-200 py-4">
    <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
      <p>© 2025 智慧教育考试系统 版权所有</p>
    </div>
  </footer>

  <script>
    // 全局变量：当前题目ID、学生ID、用户答案、是否已提交
    async function UserIdInfo(){
        try{
            const response = await fetch('/api/current-user');
            const userid = await response.json();
            return userid
        }
        catch (error){
            console.error('加载用户信息失败：',error);
        }
    }
    const STU_ID = UserIdInfo().username; // 实际项目中应从登录态获取
    // 角色切换功能
    const setupRoleSwitch = () => {
      const teacherTab = document.getElementById('teacher-tab');
      const studentTab = document.getElementById('student-tab');
      const teacherNav = document.getElementById('teacher-nav');
      const studentNav = document.getElementById('student-nav');

      teacherTab.addEventListener('click', () => {
        // 更新标签样式
        teacherTab.classList.add('bg-primary', 'text-white');
        teacherTab.classList.remove('bg-white', 'text-gray-600', 'hover:bg-gray-50');
        studentTab.classList.add('bg-white', 'text-gray-600', 'hover:bg-gray-50');
        studentTab.classList.remove('bg-primary', 'text-white');

        // 显示教师导航，隐藏学生导航
        teacherNav.classList.remove('hidden');
        studentNav.classList.add('hidden');
      });
    };

    const setupExamParticipation = () => {
  console.log('🚀 setupExamParticipation 函数已执行，事件监听器已设置。');

  // 1. 在 body 上设置全局点击监听器（事件委托）
  document.body.addEventListener('click', async (event) => {
    console.log('👆 页面被点击了！', event.target); // 打印出被点击的任何元素

    // 2. 使用 .closest() 查找被点击的元素或其父元素中，是否有 '.btn-exam' 类的按钮
    const button = event.target.closest('.btn-exam');
    console.log('🔍 查找最近的 .btn-exam 按钮，结果:', button);

    // 3. 如果没找到按钮，说明点击的不是我们关心的区域，直接结束
    if (!button) {
      console.log('❌ 没找到考试按钮，事件结束。');
      return;
    }

    console.log('✅ 找到了考试按钮！开始处理逻辑...');
    // --- 从这里开始，就是点击了有效按钮后的逻辑 ---

    // 4. 从按钮的 data 属性中获取所有需要的信息
    const canStart = button.dataset.canStart === 'true';
    const examId = button.dataset.examId;
    const examName = button.dataset.examName || '';
    const statusText = button.dataset.statusText || '';
    console.log(`📊 按钮数据: canStart=${canStart}, examId=${examId}, examName="${examName}"`);

    // 5. 检查是否可以开始考试
    if (!canStart) {
      console.log('🚫 按钮状态为不可开始，准备弹出提示。');
      alert(`当前考试状态：${statusText}。暂时无法进入考场。`);
      return;
    }

    console.log('✅ 按钮可以开始，准备显示加载状态...');
    // 6. 准备UI反馈（显示加载状态）
    const originalText = button.innerHTML;
    button.disabled = true;
    button.classList.add('opacity-70', 'cursor-not-allowed');
    button.innerHTML = '<i class="fa fa-spinner fa-spin"></i><span>正在进入...</span>';

    try {
      console.log(`🌐 准备发送网络请求到: /api/exam_schedules/${examId}/start`);
      // 7. 发送异步请求到后端
      const response = await fetch(`/api/exam_schedules/${examId}/start`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify({})
      });

      console.log('📨 收到服务器响应，状态码:', response.status);
      const result = await response.json();
      console.log('📨 响应内容:', result);

      // 8. 检查响应是否成功
      if (!response.ok || !result.success) {
        console.log('❌ 服务器返回失败，准备抛出错误。');
        throw new Error(result.message || '无法进入考试');
      }

      console.log('✅ 请求成功！准备跳转页面...');
      // 9. 根据后端返回的地址进行跳转
      if (result.redirect_url) {
        console.log('🔗 使用后端返回的 redirect_url 进行跳转:', result.redirect_url);
        window.location.href = result.redirect_url;
        return;
      }

      // 如果没有指定 redirect_url，则使用默认地址
      console.log('🔗 使用默认地址进行跳转:', `/take_exam/${examId}`);
      window.location.href = `/take_exam/${examId}`;

    } catch (error) {
      // 10. 如果发生任何错误，恢复按钮状态并提示用户
      console.error('💥 捕获到错误:', error);
      alert(error.message || `进入考试"${examName}"失败，请稍后再试。`);
      console.log('🔄 正在恢复按钮状态...');
      button.disabled = false;
      button.classList.remove('opacity-70', 'cursor-not-allowed');
      button.innerHTML = originalText;
      console.log('✅ 按钮状态已恢复。');
    }
  });
};

// 【重要】确保在页面加载完成后调用这个函数
document.addEventListener('DOMContentLoaded', () => {
  console.log('📄 页面DOM加载完毕。');
  setupExamParticipation();
});




    // 搜索功能
    const setupSearchForm = () => {
      const searchForm = document.getElementById('search-form');
      const resetBtn = document.getElementById('reset-btn');
      const examTypeSelect = document.getElementById('exam-type');
      const subjectSelect = document.getElementById('subject');

      // 构建URL参数并跳转的函数
      const performSearch = () => {
        // 获取表单数据
        const formData = new FormData(searchForm);
        const params = new URLSearchParams();

        // 添加非空参数
        if (formData.get('exam_type') && formData.get('exam_type') !== '全部类型') {
          params.append('exam_type', formData.get('exam_type'));
        }
        if (formData.get('subject') && formData.get('subject') !== '全部学科') {
          params.append('subject', formData.get('subject'));
        }
        if (formData.get('keyword')) {
          params.append('keyword', formData.get('keyword'));
        }

        // 构建新URL并跳转
        const newUrl = `${window.location.pathname}${params.toString() ? '?' + params.toString() : ''}`;
      };

      // 处理表单提交
      searchForm.addEventListener('submit', (e) => {
        e.preventDefault();
        performSearch();
      });

      // 处理下拉框变化，自动触发搜索
      examTypeSelect.addEventListener('change', performSearch);
      subjectSelect.addEventListener('change', performSearch);

      // 处理重置按钮
      resetBtn.addEventListener('click', () => {
        // 清空表单
        document.getElementById('exam-type').value = '全部类型';
        document.getElementById('subject').value = '全部学科';
        document.getElementById('keyword').value = '';

        // 提交表单
        performSearch();
      });
    };

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', () => {
      setupRoleSwitch();
      setupExamParticipation();
      setupSearchForm();
    });
  </script>
</body>
</html>